package com.letoken.platform.app.job;

import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSON;
import com.letoken.platform.app.service.AdminFundConfigService;
import com.letoken.platform.app.service.AppFundInfoService;
import com.letoken.platform.pub.constant.ConstantsValue;
import com.letoken.platform.pub.enums.LetokenApiResponseEnum;
import com.letoken.platform.pub.enums.LetokenTokenTypeEnum;
import com.letoken.platform.pub.enums.TokenTransactionStatusEnum;
import com.letoken.platform.pub.enums.TokenTransactionTypeEnum;
import com.letoken.platform.pub.exception.ApiServiceException;
import com.letoken.platform.repo.admin.dao.AppUserSwapRecordMapper;
import com.letoken.platform.repo.admin.po.AdminFundConfig;
import com.letoken.platform.repo.app.dao.AppLpLockHistoryMapper;
import com.letoken.platform.repo.app.dao.AppUserAssetsHistoryMapper;
import com.letoken.platform.repo.app.dao.AppUserWalletMapper;
import com.letoken.platform.repo.app.po.AppUserAssetsHistory;
import com.letoken.platform.repo.app.po.AppUserWallet;
import com.letoken.platform.repo.app.req.user.FundTransferReq;
import com.letoken.platform.repo.mall.po.AppLpLockHistory;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class LpUnlockJob {

    @Autowired
    AppLpLockHistoryMapper appLpLockHistoryMapper;
    @Autowired
    AppUserWalletMapper appUserWalletMapper;
    @Autowired
    AppUserAssetsHistoryMapper appUserAssetsHistoryMapper;


    @XxlJob("unlockLp")
    public  void unlockLp(){
        log.info("开始解锁任务");
        LocalDateTime now = LocalDateTime.now();
        List<AppLpLockHistory> list = appLpLockHistoryMapper.selectNeedUnLockHistorys(now);
        if (CollectionUtils.isNotEmpty(list)){
            list.forEach(x->{
                try {
                    Integer appUserWalletId ;
                    if (null == (appUserWalletId = appUserWalletMapper.checkoutTokenIdAndUserId(LetokenTokenTypeEnum.LP.getId(), x.getUserId()))){
                        log.info("找不到用户钱包ID了 {}", JSON.toJSONString(x));
                        return;
                    }
                    SpringUtil.getBean(LpUnlockJob.class).dro(x,appUserWalletId);
                    log.info("记录解锁成功 {}",x.getId());
                } catch (Exception e) {
                    log.error("记录解锁失败! {}",x.getId(),e);
                }
            });
        }
    }


    @Transactional(rollbackFor = Exception.class)
    public void dro(AppLpLockHistory h,Integer appWalletId){
        AppUserWallet appUserWallet = appUserWalletMapper.selectForUpdate(appWalletId);
        if (appUserWallet.getAvailableBalance().compareTo(BigDecimal.ZERO) < 0){
            log.info("用户 {} 钱包记录 {} 可用金额小于0，钱包账户异常");
            throw new RuntimeException("金额小于0，异常记录");
        }
        AppUserWallet newAuw = new AppUserWallet();
        newAuw.setId(appWalletId);
        newAuw.setReleasedBalance(appUserWallet.getReleasedBalance().subtract(h.getAmount()));
        newAuw.setAvailableBalance(appUserWallet.getAvailableBalance().add(h.getAmount()));
        appUserWalletMapper.updateById(newAuw);


        AppLpLockHistory newH = new AppLpLockHistory();
        newH.setId(h.getId());
        newH.setType(ConstantsValue.I_1);
        appLpLockHistoryMapper.updateById(newH);


    }



}
